package com.code2roc.jarmanage.servlet.manage;

import com.code2roc.jarmanage.db.CommandDB;
import com.code2roc.jarmanage.db.GroupDB;
import com.code2roc.jarmanage.db.ProjectDB;
import com.code2roc.jarmanage.db.WarDB;
import com.code2roc.jarmanage.depoly.DepolyPlatform;
import com.code2roc.jarmanage.model.*;
import com.code2roc.jarmanage.util.*;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@MultipartConfig
public class ImportServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Result result = Result.okResult();
        String type = req.getParameter("type");
        Part file = req.getPart("file");
        try {
            SAXReader reader = new SAXReader();
            Document document = reader.read(file.getInputStream());
            Element root = document.getRootElement();
            Element filetype = root.element("filetype");
            if (filetype.getText().equals(type + "config")) {
                List<WarDO> warDOList = new ArrayList<>();
                List<ProjectDO> projectDOList = new ArrayList<>();
                List<GroupDO> groupDOList = new ArrayList<>();
                List<CommandDO> commandDOList = new ArrayList<>();

                List<Element> dataEntityListList = root.elements("DataEntityList");
                for (Element dataEntityListListItem : dataEntityListList) {
                    List<Element> dataEntityList = dataEntityListListItem.elements("DataEntity");
                    for (Element dataEntity : dataEntityList) {
                        String tableName = dataEntity.attributeValue("tableName");
                        if (tableName.equals("DepolyProject")) {
                            if (type.equals("jar")) {
                                ProjectDO entity = ImportConvert.convertModel(ProjectDO.class, dataEntity);
                                if (ProjectDB.checkExistServiceName(entity.getServiceName())) {
                                    continue;
                                }
                                if (!StringUtil.isEmpty(entity.getDepolyPort()) && ProjectDB.checkExistDepolyPort(entity.getDepolyPort())) {
                                    continue;
                                }
                                projectDOList.add(entity);
                            } else if (type.equals("war")) {
                                WarDO entity = ImportConvert.convertModel(WarDO.class, dataEntity);
                                if (WarDB.checkExistServiceName(entity.getServiceName())) {
                                    continue;
                                }
                                if (!StringUtil.isEmpty(entity.getDepolyPort()) && WarDB.checkExistDepolyPort(entity.getDepolyPort())) {
                                    continue;
                                }
                                warDOList.add(entity);
                            }
                        } else if (tableName.equals("DepolyGroup")) {
                            GroupDO groupDO = ImportConvert.convertModel(GroupDO.class, dataEntity);
                            GroupDO dbEntity = GroupDB.selectOne(groupDO.getGroupID());
                            if (dbEntity == null) {
                                groupDOList.add(groupDO);
                            }
                        } else if (tableName.equals("ExecuteCommand")) {
                            CommandDO commandDO = ImportConvert.convertModel(CommandDO.class, dataEntity);
                            CommandDO dbEntity = CommandDB.selectOne(commandDO.getCommandID());
                            if (dbEntity == null) {
                                commandDOList.add(commandDO);
                            }
                        }
                    }
                }
                List<String> projectIDList = new ArrayList<>();
                List<String> groupIDList = new ArrayList<>();
                if (type.equals("jar")) {
                    for (ProjectDO entity : projectDOList) {
                        String jarPath = "depoly" + File.separator + entity.getServiceName().trim();
                        FileUtil.initfloderPath(jarPath);
                        entity.setJarPackagePath(jarPath);
                        String depolyBeforeParam = entity.getDepolyBeforeParam();
                        if (!EnviromentUtil.getDepolyPlaform().equals(DepolyPlatform.Windows) && !depolyBeforeParam.contains("-Djava.awt.headless=true")) {
                            depolyBeforeParam += " -Djava.awt.headless=true";
                        }
                        entity.setDepolyBeforeParam(depolyBeforeParam);
                        ProjectDB.insert(entity);
                        projectIDList.add(entity.getProjectID());
                        if (!StringUtil.isEmpty(entity.getGroupGuid())) {
                            groupIDList.add(entity.getGroupGuid());
                        }
                    }
                } else if (type.equals("war")) {
                    for (WarDO entity : warDOList) {
                        String jarPath = "depoly-war" + File.separator + entity.getServiceName().trim();
                        FileUtil.initfloderPath(jarPath);
                        entity.setJarPackagePath(jarPath);
                        String webappsPath = "depoly-war" + File.separator + entity.getServiceName().trim() + File.separator + "webapps";
                        FileUtil.initfloderPath(webappsPath);
                        String depolyBeforeParam = "-Dfile.encoding=UTF-8 ";
                        if (!EnviromentUtil.getDepolyPlaform().equals(DepolyPlatform.Windows)) {
                            depolyBeforeParam += " -Djava.awt.headless=true";
                        }
                        if(!StringUtil.isEmpty(entity.getInitMemorySize())){
                            depolyBeforeParam += " -Xms"+entity.getInitMemorySize()+"m";
                        }
                        if(!StringUtil.isEmpty(entity.getMaxMemorySize())){
                            depolyBeforeParam += " -Xmx"+entity.getMaxMemorySize()+"m";
                        }
                        entity.setDepolyBeforeParam(depolyBeforeParam);
                        String jvmParam = entity.getServiceName();
                        String param = "\"" + entity.getServiceName() + "★" + new File(jarPath).getAbsolutePath() + "★" + entity.getWarPort() + "★" + entity.getContextPath() + "★" + jvmParam + "★" + entity.getSkipScan() + "\"";
                        entity.setDepolyAfterParam(param);
                        WarDB.insert(entity);
                        projectIDList.add(entity.getProjectID());
                        if (!StringUtil.isEmpty(entity.getGroupGuid())) {
                            groupIDList.add(entity.getGroupGuid());
                        }
                    }
                }
                for (CommandDO entity : commandDOList) {
                    if (projectIDList.contains(entity.getProjectID())) {
                        CommandDB.insert(entity);
                    }
                }
                for (GroupDO entity : groupDOList) {
                    if (groupIDList.contains(entity.getGroupID())) {
                        GroupDB.insert(entity);
                    }
                }
            } else {
                result = Result.errorResult().setMsg("xml文件类型错误");
            }
        } catch (Exception e) {
            LogUtil.error(e);
            result = Result.errorResult().setMsg("解析xml文件错误");
        }
        resp.getWriter().println(result.toString());
    }
}
